package it.unibo.imola.gui;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.ui.PlatformUI;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class OpenCommandHandler extends AbstractHandler {

	private Logger logger = LoggerFactory.getLogger(getClass());

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		FileDialog fileDialog = new FileDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), SWT.OPEN);
		fileDialog.setFilterExtensions(new String[] { "*.imola", "*.txt" });
		
		String fileName = fileDialog.open();
		
		if (fileName == null || fileName.isEmpty())
			return null;
		
		if (logger.isDebugEnabled())
			logger.debug("fileName=" + fileName);

		File file = new File(fileName);
		if (file.exists()) {
			String fileContent = null;
			try {
				fileContent = FileUtils.readFileToString(file);
			} catch (IOException e) {
				MessageDialog errorDialog = new MessageDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Error", null, e.getMessage(), MessageDialog.ERROR, new String[]{"OK"}, 0);
				errorDialog.open();
			}

			if (fileContent != null) {

				if (logger.isTraceEnabled())
					logger.trace("fileContent=" + fileContent);				
				
				EditorView editorView = (EditorView) PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().findView(EditorView.ID);
				editorView.getStyledText().setText(fileContent);
				TreeView treeView = (TreeView) PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().findView(TreeView.ID);
				treeView.getTree().removeAll();
			}
			else{
				if (logger.isDebugEnabled())
					logger.debug("fileContent=null");				
			}
		}
		else{
			if (logger.isDebugEnabled())
				logger.debug("file not exists");				
		}
		return null;
	}

}
